<?php

namespace app\common\service;

use Qiniu\Auth;
use Qiniu\Storage\BucketManager;
use Qiniu\Storage\UploadManager;

require(__DIR__ . '/../../../vendor/Qiniu/autoload.php');

class QiniuService
{
    const QINIU_ACCESS_KEY = 'DeUapXGLQL_GEmFusFRSbX_HmLhLWHgA5C_GhgyA';
    const QINIU_SECRET_KEY = '9TQgJf14vTXHzIpbJ9cDMf0XJ-QLDa1DQmY3W_CL';
    const QINIU_BUCKET     = 'gnsp';

    private static function auth()
    {
        // 初始化Auth状态
        $auth = new Auth(self::QINIU_ACCESS_KEY, self::QINIU_SECRET_KEY);
        return $auth;
    }

    //获取上传凭证
    public function getUploadToken()
    {
        $auth  = $this->auth();
        $token = $auth->uploadToken(self::QINIU_BUCKET, null, 300, null, true);

        return $token;
    }

    //上传用户头像  远程地址
    public static function uploadUrlPath($img_url, $user_id)
    {
        $bucket = self::QINIU_BUCKET;
        $auth   = self::auth();

        $key = "head/" . $user_id . "/" . substr(md5(time()), 0, 5) . date('YmdHis') . rand(0, 9999) . ".jpg";

        $bucketMgr = new BucketManager($auth);
        list($ret, $err) = $bucketMgr->fetch($img_url, $bucket, $key);
        if ($err !== null) {
            return false;
        } else {
            return $key;
        }
    }

    public static function uploadImagePath($img_url, $keyPath, $ext)
    {
        $bucket = self::QINIU_BUCKET;
        $auth   = self::auth();
        $token  = $auth->uploadToken($bucket);

        $key = $keyPath . "/" . substr(md5(time()), 0, 5) . date('YmdHis') . rand(0, 9999) . "." . $ext;

        $uploadManager = new UploadManager();
        list($ret, $err) = $uploadManager->putFile($token, $key, $img_url);
        if ($err !== null) {
            return false;
        } else {
            return $key;
        }
    }

    public static function uploadHeadPath($img_url, $user_id, $ext)
    {
        $bucket = self::QINIU_BUCKET;
        $auth   = self::auth();
        $token  = $auth->uploadToken($bucket);

        $key = "head/" . $user_id . "/" . substr(md5(time()), 0, 5) . date('YmdHis') . rand(0, 9999) . ".jpg";

        $uploadManager = new UploadManager();
        list($ret, $err) = $uploadManager->putFile($token, $key, $img_url);
        if ($err !== null) {
            return false;
        } else {
            return $key;
        }

    }
}